package classes;

import java.net.URL;
import java.util.ArrayDeque;
import containers.Page;
import containers.StartContainer;

public class Main {
	public static final int PROCESS_LIMIT = 14;
	private static UserInterface myUi;
	private static PageRetriever myPR;
	private static PageParser myPP;
	private static PageAnalyzer myPA;
	private static int numProcessed;
	private static ArrayDeque<URL> urlList;
	
	public static void main(final String[] the_args) {		
		myUi = new UserInterface();
		
		StartContainer mySC = myUi.startScript();
		
		myPR = new PageRetriever();
		myPP = new PageParser();
		myPA = new PageAnalyzer(mySC.getKeywords());
		
		urlList = new ArrayDeque<URL>();
		
		numProcessed = 0;
		
		urlList.add(mySC.getSeedURL());
		Page workingPage = null;
		Page analPage = null;
		int seedOnly = 2;
		
		//loop through execution until hit page limit.
		while (numProcessed < PROCESS_LIMIT && !urlList.isEmpty()) {
			//send nextURL to PR
			//get pag6e object from retriever
			workingPage = null;
			while (workingPage == null && (!urlList.isEmpty() || seedOnly > 0)) {
				workingPage = myPR.getPageFromURL(urlList.pop());
			}
			
			seedOnly--;
			
			if (!urlList.isEmpty() || workingPage != null) {
				//send page object to parser.
				analPage = myPP.parsePage(workingPage);
				
				//get new urls from PP
				urlList.addAll(analPage.getURLs());
				
				//send new anal page to analyzer
				myPA.analyzePage(analPage);
				numProcessed++;
			}
			
			//to show working program.
			System.out.print(".");
		}
		
		//print out statistics
		myUi.endScript(myPA.tabulateStatistics());
		
//		http://css.insttech.washington.edu/~mealden/
	}
}
